#include"list.h"

LTNode* LTBuyNode(LTDateType x)
{
	LTNode* plist = (LTNode*)malloc(sizeof(LTNode));
	if (plist == NULL)
	{
		perror("malloc fail!");
		exit(1);
	}
	plist->next = plist->prev = plist;
	plist->date = x;
}

void LTPrint(LTNode* phead)
{
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		printf("%d->", pcur->date);
		pcur = pcur->next;
	}
	printf("\n");
}


LTNode* LTInit(LTNode** pphead)
{
	*pphead = LTBuyNode(-1);

}

void LTPushBack(LTNode* head, LTDateType x)
{
	assert(head);
	LTNode* newnode = LTBuyNode(x);
	newnode->next = head;
	newnode->prev = head->prev;
	newnode->prev->next = newnode;
	head->prev = newnode;
	
	
}

void LTPushFront(LTNode* phead, LTDateType x)
{
	assert(phead);
	LTNode* newnode = LTBuyNode(x);
	newnode->next = phead->next;
	phead->next->prev = newnode;
	phead->next = newnode;
	newnode->prev = phead;
}

void LTPopBack(LTNode* phead)
{
	assert(phead && phead->next != phead);
	LTNode* ret = phead->prev->prev;
	free(phead->prev);
	phead->prev = ret;
	ret->next = phead;
	
}

void LTPopFront(LTNode* phead)
{
	assert(phead && phead->next != phead);
	LTNode* ret = phead->next->next;
	free(phead->next);
	phead->next = ret;
	ret->prev = phead;
}

LTNode* LTFind(LTNode* phead, LTDateType x)
{
	LTNode* pcur = phead->next;
	while (pcur)
	{
		if (pcur->date == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}

void LTInsert(LTNode* pos, LTDateType x)
{
	assert(pos);
	LTNode* newnode = LTBuyNode(x);
	pos->next->prev = newnode;
	newnode->next = pos->next;
	pos->next = newnode;
	newnode->prev = pos;
}

void LTErase(LTNode* pos) {
	assert(pos);
	LTNode* prev = pos->prev;
	LTNode* next = pos->next;
	free(pos);
	pos = NULL;
	prev->next = next;
	next->prev = prev;

}

void LTDestroy(LTNode* phead)
{
	assert(phead);
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		LTNode* next = pcur->next;
		free(pcur);
		pcur = next;

	}
	free(phead);
	phead = NULL;
}